<template>
  <div class="fulltable">
    <div class="full">
      <div class="add">  
        <button class="button" @click="showAddModal = true" v-if="isSuperman">➕新增</button>  
      </div>  
      <div class="search-box">  
        <el-input v-model="searchCno" placeholder="搜索会议室号" style="width: 200px;" clearable></el-input>  
      </div>
    <el-table
    :data="filteredBoardroomData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" 
    :height="tableHeight"
    border
    style="width: 100%">
    <el-table-column
      prop="cno"
      label="房间号"
      width="100">
    </el-table-column>
    <el-table-column
      prop="number"
      label="可容纳人数"
      width="180"
      >
    </el-table-column>
    <el-table-column
      prop="notes"
      label="备注"
      :width="isSuperman ? '200' : ''"
      >
    </el-table-column>
      <el-table-column label="操作" v-if="isSuperman">  
        <template slot-scope="scope">   
          <el-button type="primary" size="small" @click="editItem(scope.row)">编辑</el-button> <!-- 新增的编辑按钮 -->  
          <el-button type="danger" size="small" @click="deleteItem(scope.row)">删除</el-button>  
        </template>  
      </el-table-column>  
  </el-table>
      <div class="paging">
        <el-pagination  
          @size-change="handleSizeChange"  
          @current-change="handleCurrentChange"  
          :current-page="currentPage"  
          :page-sizes="[5,10, 20, 40, 60]"  
          :page-size="pageSize"  
          :pager-count="4"  
          layout="total, sizes, prev, pager, next, jumper"  
          :total="filteredBoardroomData.length">  
        </el-pagination>   
      </div>
  </div>

<el-dialog :title="newItem.id ? '编辑会议室' : '新增会议室'" :visible.sync="showAddModal" width="30%">  
  <el-form :model="newItem" label-width="80px" ref="newItemForm">  
    <el-form-item label="房间号" prop="cno" :rules="[{ required: true, message: '房间号不能为空' }]">  
      <el-input v-model="newItem.cno"></el-input>  
    </el-form-item>  
    <el-form-item label="可容纳人数" prop="number" :rules="[{ required: true, message: '可容纳人数不能为空' }]">  
      <el-input v-model="newItem.number"></el-input>  
    </el-form-item>  
    <el-form-item label="备注" prop="notes">  
      <el-input v-model="newItem.notes"></el-input>  
    </el-form-item>  
  </el-form>  
  <span slot="footer" class="dialog-footer">  
    <el-button @click="handShowAddModal">取 消</el-button>  
    <el-button type="primary" @click="saveNewItem">确 定</el-button>  
  </span>  
</el-dialog>
  </div>
</template>

<script>
import {getBoardroomList,addBoardroom,deleteBoardroomById,updateBoardroom } from '@/api/boardroom';
import { jwtDecode } from 'jwt-decode'; // 导入 jwt-decode 库
import {addLog} from '@/api/log';
export default {
  data(){
    return {
      logItem:{
              mn:'',
              opn:'',
              res:''
      },
      boardroomData:[],
        currentPage: 1,  
        pageSize: 5  ,
        tableHeight: 300,  
        maxTableHeight: 700, // 最大高度 600px  
        minTableHeight: 300,
        showAddModal: false,  
        newItem: {  
          cno: '',  
          number: '',  
          notes: ''  
        },
        searchCno: '', // 新增搜索条件    
        isSuperman: this.checkUserRole(), // 检查用户角色并设置 
    }
  },
  computed: {  
  filteredBoardroomData() {  
      return this.boardroomData.filter(item => {  
        return item.cno.includes(this.searchCno); // 过滤会议室号  
      });  
    }  
  },
  created(){
    getBoardroomList().then(response=>{
      this.boardroomData = response.data
      this.calculateTableHeight() 
      console.log(response.data)
    }).catch(error =>{
      console.log(error)
      this.tableHeight = this.minTableHeight  
    })
  },
    watch:{
  currentPage() {  
    this.calculateTableHeight()  
  },  
  pageSize() {  
    this.calculateTableHeight()  
  }
  },
  methods:{
    editItem(row) {  
  // 复制待编辑的行数据到 newItem 中以便用户可以修改  
  this.newItem = { ...row };  
  this.showAddModal = true; // 显示添加/编辑对话框  
  console.log("本行数据",this.newItem)
}  ,
    handleSizeChange(val) {  
      this.pageSize = val;  
      this.currentPage = 1;  
      this.logItem.mn = "handleSizeChange";
      this.logItem.opn = "改变每页显示的会议室数量-会议室管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
    handleCurrentChange(val) {  
      this.currentPage = val;  
      this.logItem.mn = "handleCurrentChange";
      this.logItem.opn = "改变页码-会议室管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
  calculateTableHeight() {  
    // 获取当前页展示的数据量  
    const currentPageData = this.boardroomData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);  
    
    // 每行高度为 50px，再加上表头高度 50px，得到总高度  
    let height = (currentPageData.length + 1) * 60 
    // 限制高度在 minTableHeight 和 maxTableHeight 之间  
    this.tableHeight = Math.max(this.minTableHeight, Math.min(height, this.maxTableHeight))  
  },
saveNewItem() {  
  this.$refs.newItemForm.validate((valid) => {  
    if (valid) {  
      if (this.newItem.id) {  
        // 调用后端接口更新会议室  
        updateBoardroom(this.newItem).then(response => {  
          this.$message.success('会议室更新成功');  
          this.logItem.mn = "saveNewItem";
          this.logItem.opn = "编辑会议室";
          this.logItem.res = "true";
          addLog(this.logItem);
          window.location.reload();  
        }).catch(error => {  
          this.$message.error('会议室更新失败');  
          this.logItem.mn = "saveNewItem";
          this.logItem.opn = "编辑会议室";
          this.logItem.res = "false";
          addLog(this.logItem);
          console.error(error);  
        });  
      } else {  
        // 调用后端接口保存新会议室  
        addBoardroom(this.newItem)  
          .then(response => {  
            this.$message.success('新会议室添加成功');   
            this.logItem.mn = "saveNewItem";
            this.logItem.opn = "新增会议室";
            this.logItem.res = "true";
            addLog(this.logItem);
            window.location.reload();  
          })  
          .catch(error => {  
            this.$message.error('新会议室添加失败');  
            this.logItem.mn = "saveNewItem";
            this.logItem.opn = "新增会议室";
            this.logItem.res = "false";
            addLog(this.logItem);
            console.error(error);  
          });  
      }  
      this.showAddModal = false;  
      this.newItem = {};  
    } else {  
      // 表单验证失败的处理  
      return false;  
    }  
  });  
},  
  handShowAddModal(){
    this.showAddModal = false;
    this.newItem = {}
  },
  deleteItem(row) {  
  this.$confirm('确定要删除此会议室吗?', '警告', {  
    confirmButtonText: '确定',  
    cancelButtonText: '取消',  
    type: 'warning'  
  }).then(() => {  
    deleteBoardroomById(row.id).then(response => {  
      // 确保删除成功后更新 boardroomData  
      this.boardroomData = this.boardroomData.filter(item => item.id !== row.id);  
      this.$message.success('会议室删除成功');  
      this.logItem.mn = "deleteItem";
      this.logItem.opn = "删除会议室";
      this.logItem.res = "true";
      addLog(this.logItem);
      window.location.reload()
    }).catch(error => {  
      console.error("删除失败:", error);  
      this.logItem.mn = "deleteItem";
      this.logItem.opn = "删除会议室";
      this.logItem.res = "false";
      addLog(this.logItem);
      this.$message.error('会议室删除失败');  
    });  
  }).catch(() => {  
    this.$message.info('已取消删除');  
  });  
},
checkUserRole() {  
  const token = localStorage.getItem('token'); // 从本地存储获取 token  
  if (token) {  
    const decodedToken = jwtDecode(token); // 解码 token  
    return decodedToken.role === 'SUPERMAN'; // 检查角色  
  }  
  return false; // 无 token 返回 false  
},
} 
  
}
</script>

<style lang="less" scoped>
.fulltable{
  margin-top: 20px;
  height: 700px;

}
.full{
  height: 800px;
  margin: 0;
  padding: 0;
  background: pink;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;
}
.add{
  padding: 10px;
}
/deep/.el-table .cell {  
  color: black;
}  
.button{
  background: #788fd3;
  color: white;
}

.paging{
  margin: 0;
  padding: 0;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;

  /deep/ .el-pagination {
    display: flex;  
    justify-content: flex-end;  
  }
}
</style>